/**
 * PopularTeacherServiceImpl.java
 * com.sftz.modules.weixin.popularTeacher.service.impl
 * Copyright (c) 2018, 北京科技有限公司版权所有.
*/

package com.sftz.modules.minapp.popularTeacher.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.SqlManager;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import com.sftz.assets.entities.FansTabEntity;
import com.sftz.assets.entities.FollowingEntity;
import com.sftz.assets.entities.VUserTypeEntity;
import com.sftz.assets.enums.AttentionEnum;
import com.sftz.assets.enums.DataStatusEnum;
import com.sftz.modules.minapp.popularTeacher.dto.PopularEntryForm;
import com.sftz.modules.minapp.popularTeacher.dto.QueryByIdDto;
import com.sftz.modules.minapp.popularTeacher.service.PopularTeacherService;
import com.sftz.modules.minapp.user.cache.RedissionUserCache;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;
import com.uxuexi.core.db.util.DbSqlUtil;
import com.uxuexi.core.web.chain.support.JsonResult;

@IocBean(name = "popularTeacherService")
public class PopularTeacherServiceImpl implements PopularTeacherService {

	@Inject
	private IDbDao dbDao;

	@Inject
	private SqlManager sqlManager;

	private static final int followed = 1;//已关注

	private static final int unfollowed = 2;//未关注

	private static final int userIdStatus = -1;//代表当前登陆失效，则关注状态就为未关注

	@Override
	public Object queryTeacherType(PopularEntryForm form) {
		String token = form.getToken();
		Integer userId = userIdStatus;
		if (!Util.isEmpty(token)) {
			try {
				userId = RedissionUserCache.getUserId(token);
			} catch (Exception e) {
				userId = userIdStatus;
				//e.printStackTrace();
			}
		}
		Map<String, Object> obj = new HashMap<String, Object>();
		//查询所有分类
		List<VUserTypeEntity> typeList = dbDao.query(VUserTypeEntity.class,
				Cnd.where("status", "=", DataStatusEnum.ENABLE.intKey()), null);
		obj.put("teacherType", typeList);
		//默认展示所有老师列表
		List<QueryByIdDto> queryTypeById = queryTypeById(0, userId, form.getSearchPageNum(), form.getCallbackcount());
		obj.put("teacherList", queryTypeById);
		return obj;
	}

	@Override
	public Object queryTypeId(Integer id, String token, Integer searchPageNum, Integer callbackcount) {
		Integer userId = userIdStatus;
		try {
			userId = RedissionUserCache.getUserId(token);
		} catch (Exception e) {
			userId = userIdStatus;
			//e.printStackTrace();
		}
		Map<String, Object> obj = new HashMap<String, Object>();
		List<QueryByIdDto> queryTypeById = queryTypeById(id, userId, searchPageNum, callbackcount);
		obj.put("teacherList", queryTypeById);
		return obj;
	}

	public List<QueryByIdDto> queryTypeById(Integer id, Integer userId, Integer searchPageNum, Integer callbackcount) {
		int start = (searchPageNum - 1) * callbackcount;
		Sql popVuser;
		if (id == 0) {
			popVuser = Sqls.create(sqlManager.get("minapp_popularTeacher_popular_teacher_not_id"));
		} else {
			popVuser = Sqls.create(sqlManager.get("minapp_popularTeacher_popular_teacher"));
			popVuser.setParam("id", id);
		}
		popVuser.setParam("fansStatus", AttentionEnum.ATTENTION.intKey());
		popVuser.setParam("start", start);
		popVuser.setParam("end", callbackcount);
		List<QueryByIdDto> showVuser = DbSqlUtil.query(dbDao, QueryByIdDto.class, popVuser);
		for (QueryByIdDto queryById : showVuser) {
			if (userId.equals(userIdStatus)) {
				queryById.setStatus(unfollowed);
			} else {
				//查询当前登陆者是否关注了此人
				FollowingEntity follow = dbDao.fetch(
						FollowingEntity.class,
						Cnd.where("userId", "=", userId).and("followingId", "=", queryById.getId())
								.and("status", "=", AttentionEnum.ATTENTION.intKey()));
				if (Util.isEmpty(follow)) {
					queryById.setStatus(unfollowed);
				} else {
					queryById.setStatus(followed);
				}
			}
		}
		return showVuser;
	}

	@Override
	public Object follow(Integer id, String token, Integer status) {
		Integer userId = RedissionUserCache.getUserId(token);
		if (id.equals(userId)) {
			return JsonResult.error("您不能关注自己!");
		}
		//如果点击之前的状态为已关注，则一定存在关注数据，只需修改状态和粉丝数量
		if (!Util.isEmpty(id) && !Util.isEmpty(userId) && !Util.isEmpty(status)) {
			FollowingEntity follow = dbDao.fetch(FollowingEntity.class,
					Cnd.where("userId", "=", userId).and("followingId", "=", id));
			FansTabEntity fans = dbDao.fetch(FansTabEntity.class,
					Cnd.where("userId", "=", id).and("fansId", "=", userId));
			if (!Util.isEmpty(follow) && status == followed) {
				dbDao.update(FollowingEntity.class, Chain.make("status", unfollowed),
						Cnd.where("id", "=", follow.getId()));
				if (Util.isEmpty(fans)) {
					dbDao.insert(FansTabEntity.class, Chain.make("userId", id).add("fansId", userId));
				} else {
					dbDao.update(FansTabEntity.class, Chain.make("fansStatus", unfollowed),
							Cnd.where("id", "=", fans.getId()));
				}
				return JsonResult.success("取消关注成功!");
			} else if (!Util.isEmpty(follow) && status == unfollowed) {
				dbDao.update(FollowingEntity.class, Chain.make("status", followed),
						Cnd.where("id", "=", follow.getId()));
				if (Util.isEmpty(fans)) {
					dbDao.insert(FansTabEntity.class, Chain.make("userId", id).add("fansId", userId));
				} else {
					dbDao.update(FansTabEntity.class, Chain.make("fansStatus", followed),
							Cnd.where("id", "=", fans.getId()));
				}
				return JsonResult.success("关注成功!");
			} else {
				dbDao.insert(FollowingEntity.class, Chain.make("userId", userId).add("followingId", id));
				dbDao.insert(FansTabEntity.class, Chain.make("userId", id).add("fansId", userId));
				return JsonResult.success("关注成功!");
			}
		}
		return JsonResult.error("操作失败!");
	}

}
